/**
 * 脑波频域泳道图组件
 * 
 * 该文件实现了一个自适应的泳道图组件，用于显示脑波频域数据
 * 横轴表示时间，纵轴表示各频域的比例
 * 五个频域（Delta、Theta、Alpha、Beta、Gamma）以不同颜色的覆盖区域显示
 * 
 * 使用方法：
 * - 使用Jetpack Compose的Canvas进行自定义绘制
 * - 支持实时数据更新和平滑动画过渡
 * - 自适应布局，可以放置在任何容器中
 * 
 * 原理：
 * - 将时间轴映射到Canvas的宽度
 * - 将频域比例映射到Canvas的高度
 * - 使用Path绘制平滑的覆盖区域
 * - 通过State管理数据更新和动画
 */

package com.example.brain_wave.ui.components

import androidx.compose.animation.core.*
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.layout.*
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.*
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlin.math.max
import kotlin.math.min
import com.example.brain_wave.ui.components.SharedTimeAxis
import com.example.brain_wave.ui.components.calculateTimeAxisData

/**
 * 泳道图主组件
 * 
 * @param dataPoints 脑波数据点列表
 * @param config 图表配置
 * @param modifier 修饰符
 * @param slidingController 滑动控制器（可选）
 */
@Composable
fun SwimLaneChart(
    dataPoints: List<BrainWaveDataPoint>,
    config: SwimLaneChartConfig = SwimLaneChartConfig(),
    modifier: Modifier = Modifier,
    slidingController: SlidingChartController? = null
) {
    // 使用滑动控制器或直接使用数据
    val displayData = if (slidingController != null) {
        val visibleData by slidingController.visibleData.collectAsState()
        
        // 更新控制器数据
        LaunchedEffect(dataPoints) {
            slidingController.updateData(dataPoints)
        }
        
        visibleData
    } else {
        dataPoints
    }
    
    // 动画状态
    val animatedProgress by animateFloatAsState(
        targetValue = if (displayData.isNotEmpty()) 1f else 0f,
        animationSpec = tween(config.animationDurationMs),
        label = "chart_animation"
    )
    
    Column(
        modifier = modifier
            .fillMaxWidth()
            .background(config.backgroundColor)
            .padding(16.dp)
    ) {
        // 图例
        if (config.showLabels) {
            FrequencyLegend()
            Spacer(modifier = Modifier.height(16.dp))
        }
        
        // 主图表区域
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(300.dp)
                .let { mod ->
                    if (slidingController != null) {
                        mod.pointerInput(Unit) {
                             detectDragGestures { change, dragAmount ->
                                 // 将像素拖拽转换为时间偏移（毫秒）
                                 // 假设每像素代表100毫秒
                                 val deltaMs = (dragAmount.x * -100).toLong()
                                 slidingController.slide(deltaMs)
                             }
                         }
                    } else {
                        mod
                    }
                }
        ) {
            // 背景网格
            if (config.showGrid) {
                GridBackground(config = config)
            }
            
            // 频域标签（左侧）
            if (config.showLabels) {
                FrequencyLabels(
                    modifier = Modifier
                        .fillMaxHeight()
                        .width(60.dp),
                    textColor = config.textColor
                )
            }
            
            // 主图表Canvas
            Canvas(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(start = if (config.showLabels) 60.dp else 0.dp)
            ) {
                if (displayData.isNotEmpty()) {
                    drawSwimLanes(
                        dataPoints = displayData,
                        config = config,
                        animationProgress = animatedProgress
                    )
                }
            }
            
            // 时间轴标签（底部）
            if (config.showLabels && displayData.isNotEmpty()) {
                val timeAxisData = calculateTimeAxisData(displayData)
                SharedTimeAxis(
                    timeAxisData = timeAxisData,
                    textColor = config.textColor,
                    modifier = Modifier
                        .align(Alignment.BottomCenter)
                        .fillMaxWidth()
                        .padding(start = 60.dp)
                )
            }
        }
    }
}

/**
 * 图表标题
 */
@Composable
private fun ChartHeader() {
    Text(
        text = "脑波频域分析",
        style = MaterialTheme.typography.headlineSmall,
        color = Color.White,
        fontWeight = FontWeight.Bold
    )
}

/**
 * 频域图例
 */
@Composable
private fun FrequencyLegend() {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        BrainWaveFrequency.values().forEach { frequency ->
            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(4.dp)
            ) {
                Box(
                    modifier = Modifier
                        .size(12.dp)
                        .background(frequency.color, CircleShape)
                )
                Text(
                    text = frequency.displayName,
                    color = Color.White,
                    fontSize = 12.sp
                )
            }
        }
    }
}

/**
 * 网格背景
 */
@Composable
private fun GridBackground(config: SwimLaneChartConfig) {
    Canvas(modifier = Modifier.fillMaxSize()) {
        val width = size.width
        val height = size.height
        
        // 绘制水平网格线（每20%一条）
        for (i in 1..4) {
            val y = height * i / 5f
            drawLine(
                color = config.gridColor,
                start = Offset(0f, y),
                end = Offset(width, y),
                strokeWidth = 1.dp.toPx()
            )
        }
        
        // 绘制垂直网格线（每25%一条）
        for (i in 1..3) {
            val x = width * i / 4f
            drawLine(
                color = config.gridColor,
                start = Offset(x, 0f),
                end = Offset(x, height),
                strokeWidth = 1.dp.toPx()
            )
        }
    }
}

/**
 * 频域标签（左侧）
 */
@Composable
private fun FrequencyLabels(
    modifier: Modifier = Modifier,
    textColor: Color
) {
    Column(
        modifier = modifier,
        verticalArrangement = Arrangement.SpaceEvenly,
        horizontalAlignment = Alignment.End
    ) {
        // 从上到下：100%, 80%, 60%, 40%, 20%, 0%
        listOf("100%", "80%", "60%", "40%", "20%", "0%").forEach { label ->
            Text(
                text = label,
                color = textColor,
                fontSize = 10.sp,
                modifier = Modifier.padding(end = 8.dp)
            )
        }
    }
}

/**
 * 时间轴标签（底部）
 */
@Composable
private fun TimeAxisLabels(
    dataPoints: List<BrainWaveDataPoint>,
    config: SwimLaneChartConfig,
    modifier: Modifier = Modifier
) {
    if (dataPoints.isEmpty()) return
    
    val startTime = dataPoints.first().timestamp
    val endTime = dataPoints.last().timestamp
    
    Row(
        modifier = modifier.padding(top = 8.dp),
        horizontalArrangement = Arrangement.SpaceBetween
    ) {
        // 显示5个时间点：开始、1/4、中间、3/4、结束
        listOf(0f, 0.25f, 0.5f, 0.75f, 1f).forEach { ratio ->
            val time = startTime + ((endTime - startTime) * ratio).toLong()
            val formattedTime = formatTimeToHMS(time)
            Text(
                text = formattedTime,
                color = config.textColor,
                fontSize = 10.sp
            )
        }
    }
}

/**
 * 格式化时间为 hh时mm分ss秒 格式
 */
private fun formatTimeToHMS(timestamp: Long): String {
    val calendar = java.util.Calendar.getInstance()
    calendar.timeInMillis = timestamp
    
    val hour = calendar.get(java.util.Calendar.HOUR_OF_DAY)
    val minute = calendar.get(java.util.Calendar.MINUTE)
    val second = calendar.get(java.util.Calendar.SECOND)
    
    return String.format("%02d时%02d分%02d秒", hour, minute, second)
}

/**
 * 绘制泳道区域
 */
private fun DrawScope.drawSwimLanes(
    dataPoints: List<BrainWaveDataPoint>,
    config: SwimLaneChartConfig,
    animationProgress: Float
) {
    if (dataPoints.isEmpty()) return
    
    val width = size.width
    val height = size.height
    
    // 计算时间范围
    val startTime = dataPoints.first().timestamp
    val endTime = dataPoints.last().timestamp
    val timeRange = max(endTime - startTime, 1L)
    
    // 为每个频域绘制覆盖区域
    val frequencies = BrainWaveFrequency.values()
    
    // 从下往上绘制，确保正确的层叠效果
    for (frequencyIndex in frequencies.indices) {
        val frequency = frequencies[frequencyIndex]
        
        // 创建路径
        val path = Path()
        var isFirstPoint = true
        
        // 绘制上边界
        dataPoints.forEachIndexed { index, dataPoint ->
            val x = (dataPoint.timestamp - startTime).toFloat() / timeRange * width * animationProgress
            
            // 计算累积高度（从底部开始）
            var cumulativeRatio = 0f
            for (i in 0..frequencyIndex) {
                cumulativeRatio += dataPoint.getRatioForFrequency(frequencies[i])
            }
            
            val y = height * (1f - cumulativeRatio)
            
            if (isFirstPoint) {
                path.moveTo(x, y)
                isFirstPoint = false
            } else {
                path.lineTo(x, y)
            }
        }
        
        // 绘制下边界（反向）
        for (index in dataPoints.indices.reversed()) {
            val dataPoint = dataPoints[index]
            val x = (dataPoint.timestamp - startTime).toFloat() / timeRange * width * animationProgress
            
            // 计算累积高度（不包括当前频域）
            var cumulativeRatio = 0f
            for (i in 0 until frequencyIndex) {
                cumulativeRatio += dataPoint.getRatioForFrequency(frequencies[i])
            }
            
            val y = height * (1f - cumulativeRatio)
            path.lineTo(x, y)
        }
        
        path.close()
        
        // 绘制填充区域
        drawPath(
            path = path,
            color = frequency.color.copy(alpha = 0.8f)
        )
        
        // 绘制边界线
        drawPath(
            path = path,
            color = frequency.color,
            style = Stroke(width = 1.dp.toPx())
        )
    }
}